package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;

/**
 * 腾讯utils
 */
public class TxIpLocation {

    /**
     * 返回城市
     * @param request
     * @return
     */
    public static String CityValidation(HttpServletRequest request)
    {
        String i=  getIpAddr(request);
        String http= HttpUtils.doGet("https://apis.map.qq.com/ws/location/v1/ip?ip="+i+"&key=JFSBZ-LQB6S-SSQOA-64J6A-EOM25-7CBBO");
        JSONObject jsonObject=JSONObject.parseObject(http);

        String status= jsonObject.getString("status");
        if (status.equals("382")){
            return String.valueOf(0);
        }

        String a= jsonObject.getString("result");
        JSONObject b=JSONObject.parseObject(a);


        String c= b.getString("ad_info");
        JSONObject d=JSONObject.parseObject(c);

        String e= d.getString("city");
        return e;
    }


    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
